/*
 * @Date: 2022-09-16 09:09:44
 * @LastEditTime: 2022-09-16 09:24:01
 */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  // const hasToken = getToken()
  const hasToken = store.state.user.token

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name

      if (hasGetUserInfo) {
        next()
      } else {
        try {
          await store.dispatch('user/getInfo')

          // 一定要加 to
          // 动态路由刷新问题,在动态生成的路由页面刷新,就会空白页
          // 第一次获取到是静态路由, 此时路由匹配, 没有找到路径
          // 然后动态才添加成功, 此时路由已经完成匹配, 所有空白页
          next(to)
        } catch (error) {
          await store.dispatch('user/reset')
          // 会报 Property "visible" must be accessed with "$data.visible" because properties... 的错
          // 因为 Message.error() 或 Message() 接收类型 string/VNode，而现在是个数组，所以报错。
          // Message.error(error || 'Has Error')
          Message.error({ message: error || 'Has Error' })
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
